import React, { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Button } from '@tarojs/components';
import './index.scss';
import { getMemberPackagesApi, createPaymentOrderApi, queryPaymentOrderApi, getOpenidStatusApi } from '../../api/payment';

interface PackageType {
  id: number;
  price: number;
  duration: string;
  original_price: number;
  discount: string;
  description: string;
  button_text: string;
  button_type: string;
}

interface BenefitType {
  id: number;
  title: string;
  items: string[];
}

const MemberPayPage: React.FC = () => {
  const [packages, setPackages] = useState<PackageType[]>([]);
  const [benefits, setBenefits] = useState<BenefitType[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string>('');

  // 从后端获取会员信息
  useEffect(() => {
    fetchMemberData();
  }, []);

  const fetchMemberData = async () => {
    try {
      setLoading(true);
      setError('');
      
      // 调用后端API获取所有会员相关信息
      const response = await getMemberPackagesApi();

      if (response.code === 0) {
        const { packages: packageData, benefits: benefitData } = response.data;
        setPackages(packageData);
        setBenefits(benefitData);
      } else {
        setError(response.message || '获取会员信息失败');
        // 如果API失败，使用默认数据作为降级方案
        setPackages(getDefaultPackages());
        setBenefits(getDefaultBenefits());
      }
    } catch (err) {
      console.error('获取会员数据失败:', err);
      setError('网络请求失败，请稍后重试');
      // 网络失败时使用默认数据
      setPackages(getDefaultPackages());
      setBenefits(getDefaultBenefits());
    } finally {
      setLoading(false);
    }
  };

  // 默认套餐数据（作为降级方案）
  const getDefaultPackages = (): PackageType[] => {
    return [
      {
        id: 1,
        price: 800,
        duration: '1年',
        original_price: 1600,
        discount: '限时特惠',
        description: '首充：买1年送1年 每天仅需1元！',
        button_text: '立即开通',
        button_type: 'primary'
      },
      {
        id: 2,
        price: 1500,
        duration: '2年',
        original_price: 1600,
        discount: '93折',
        description: '立省100元',
        button_text: '立即购买',
        button_type: 'secondary yellow'
      },
      {
        id: 3,
        price: 2000,
        duration: '3年',
        original_price: 2400,
        discount: '尊贵体验',
        description: '立省400元',
        button_text: '尊享权益',
        button_type: 'secondary blue'
      }
    ];
  };

  // 默认权益数据（作为降级方案）
  const getDefaultBenefits = (): BenefitType[] => {
    return [
      {
        id: 1,
        title: '【专属特权】',
        items: ['优先响应', '搜索推荐', '专属客服']
      }
    ];
  };

  // 处理续费按钮点击
  const handleRenew = async (pkg: PackageType) => {
    try {
      // 显示加载提示
      Taro.showLoading({ title: '正在创建订单...' });
      await Taro.login(
        {
          success: async(res) => {
            console.log('获取登录凭证成功:', res);
            await paymentOrder(pkg, res.code);
          },
          fail: err => {
            console.error('获取登录凭证失败:', err);
            Taro.showToast({
              title: '订单创建失败：获取微信凭证失败',
              icon: 'none'
            });
          }
        }
      )
    } catch (error) {
      // 处理整个流程中的异常
      Taro.hideLoading();
      console.error('支付过程出错:', error);
      Taro.showToast({
        title: '支付过程出错，请重试',
        icon: 'none'
      });
    }
  };

  const paymentOrder = async (pkg: PackageType, code: string) => {
    try {
      // 调用后端接口创建支付订单
      const response = await createPaymentOrderApi({
        product_name: `会员套餐-${pkg.duration}`,
        price: pkg.price,
        package_id: pkg.id,
        code: code
      });
      
      // 隐藏加载提示
      Taro.hideLoading();
      
      if (response.code === 200) {
        // 从response.data中提取订单信息和支付参数
        const { order_info, pay_params } = response.data;

          // 调用微信支付，使用await等待支付结果
          const payResult = await Taro.requestPayment({
            ...pay_params,
            // Taro.requestPayment会返回Promise，不需要success/fail回调
          });
          
          // 支付成功后的处理
          console.log('支付成功:', payResult);
          
          // 支付成功后查询订单状态，确保权益发放
          Taro.showLoading({ title: '正在处理...' });
          
          // 根据微信支付文档，需要调用查询订单API确认订单状态
          // 实现重试机制确保订单状态查询的可靠性
          let queryAttempts = 0;
          const maxQueryAttempts = 3;
          const queryRetryDelay = 1000; // 1秒重试间隔
          let orderStatusConfirmed = false;
          let queryResponseData = null;
          
          while (queryAttempts < maxQueryAttempts && !orderStatusConfirmed) {
            try {
              const queryResponse = await queryPaymentOrderApi(order_info.out_trade_no);
              
              if (queryResponse.code === 0) {
                queryResponseData = queryResponse.data;
                const { trade_state } = queryResponseData;
                
                console.log(`订单状态查询第 ${queryAttempts + 1} 次结果:`, queryResponse.data);
                
                // 检查交易状态是否为最终状态
                const finalTradeStates = ['SUCCESS', 'PAYERROR', 'CLOSED', 'REVOKED'];
                
                if (finalTradeStates.includes(trade_state)) {
                  orderStatusConfirmed = true;
                  break;
                }
              } else {
                console.error(`订单查询第 ${queryAttempts + 1} 次失败:`, queryResponse.message);
              }
            } catch (queryError) {
              console.error(`订单状态查询第 ${queryAttempts + 1} 次遇到错误:`, queryError);
            }
            
            queryAttempts++;
            
            // 重试延迟
            if (queryAttempts < maxQueryAttempts && !orderStatusConfirmed) {
              await new Promise(resolve => setTimeout(resolve, queryRetryDelay));
            }
          }
          
          // 处理最终查询结果
          if (orderStatusConfirmed && queryResponseData?.trade_state === 'SUCCESS') {
            // 支付成功后的处理
            Taro.showToast({
              title: '支付成功',
              icon: 'success'
            });
            
            // 跳转到支付成功页面
            setTimeout(() => {
              Taro.navigateTo({ url: '/pages/payment-success/index' });
            }, 1500);
          } else {
            // 订单状态异常或查询失败
            const finalTradeState = queryResponseData?.trade_state || 'UNKNOWN';
            
            if (finalTradeState === 'UNKNOWN') {
              // 查询失败超过最大尝试次数
              console.error('订单状态查询超过最大尝试次数，最终状态未知');
              
              // 根据微信支付文档，即使查询失败，也应提示用户支付完成
              Taro.showToast({
                title: '支付完成，订单正在处理',
                icon: 'success'
              });
              setTimeout(() => {
                Taro.navigateTo({ url: '/pages/payment-success/index' });
              }, 1500);
            } else {
              // 支付失败或订单关闭
              console.error('支付失败，交易状态:', finalTradeState);
              Taro.showToast({
                title: `支付未完成: ${finalTradeState}`,
                icon: 'none'
              });
            }
          }
      }
          Taro.hideLoading();
      } catch (paymentError) {
        // 处理支付失败的情况
        console.log('支付失败:', paymentError);
        
        // 根据微信支付文档，支付失败包括用户取消支付和其他错误
        if (paymentError.errMsg === 'requestPayment:fail cancel') {
          // 用户取消支付
          Taro.showToast({
            title: '您已取消支付',
            icon: 'none'
          });
        } else {
          // 其他支付错误
          Taro.showToast({
            title: `支付失败: ${paymentError.errMsg}`,
            icon: 'none'
          });
        }
      }
  }

  return (
    <View className="member-pay-page">
      {/* 顶部标题栏 */}
      <View className="top-bar">
        <Text className="page-title">会员续费</Text>
      </View>

      {/* 加载状态 */}
      {loading && (
        <View className="loading-container">
          <Text className="loading-text">加载中...</Text>
        </View>
      )}

      {/* 错误提示 */}
      {error && (
        <View className="error-container">
          <Text className="error-text">{error}</Text>
          <Button onClick={fetchMemberData} className="retry-button">
            重试
          </Button>
        </View>
      )}

      {/* 套餐选择区域 */}
      <View className="packages-container">
        {packages.map((pkg) => (
          <View key={pkg.id} className="package-card">
            {pkg.discount && (
              <View className="discount-badge">
                <Text className="discount-text">{pkg.discount}</Text>
              </View>
            )}
            <View className="package-content">
              <View className="price-section">
                <Text className="price">{pkg.price}</Text>
                <Text className="unit">元/{pkg.duration}</Text>
                {pkg.original_price > pkg.price && (
                  <Text className="original-price">¥{pkg.original_price}</Text>
                )}
              </View>
              <Text className="description">{pkg.description}</Text>
              <Button 
                className={`renew-button ${pkg.button_type}`}
                onClick={() => handleRenew(pkg)}
                style={{ border: 'none' }}
              >
                {pkg.button_text}
              </Button>
            </View>
          </View>
        ))}
      </View>

      {/* 会员权益部分 */}
      <View className="benefits-section">
        <Text className="benefits-title">会员权益</Text>
        <View className="benefits-grid">
          {benefits.map((benefit) => (
            <View key={benefit.id} className="benefit-card">
              <Text className="benefit-title">{benefit.title}</Text>
              <View className="benefit-items">
                {benefit.items.map((item, index) => (
                  <View key={index} className="benefit-item">
                    <View className="check-icon">✓</View>
                    <Text className="benefit-text">{item}</Text>
                  </View>
                ))}
              </View>
            </View>
          ))}
        </View>
      </View>

      {/* 底部提示 */}
      <View className="bottom-notice">
        <Text className="notice-text">会员权益一经开通，不支持退款</Text>
        <Text className="notice-text">如有疑问，请联系客服</Text>
      </View>
    </View>
  );
};

export default MemberPayPage;